package com.mt.fpb.common.config;


import cn.hutool.core.codec.Base64;
import com.mt.fpb.common.exception.GlobalException;
import com.mt.fpb.common.util.JsonUtil;
import com.mt.fpb.common.util.RedisUtil;
import com.mt.fpb.mapper.AuthPerssionMapper;
import com.mt.fpb.mapper.UserMapper;
import com.mt.fpb.model.AuthPerssion;
import com.mt.fpb.model.TWarning;
import com.mt.fpb.model.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 权限认证
 */
@CrossOrigin
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Resource
    RedisUtil redis;

    @Autowired
    private AuthPerssionMapper authPerssionMapper;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {


        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(AuthUserPerssion.class)) {
            AuthUserPerssion authUserPerssion = method.getAnnotation(AuthUserPerssion.class);
            if (authUserPerssion.required()) {

String str = httpServletRequest.getHeader("moduleId");
                if(StringUtils.isEmpty(httpServletRequest.getHeader("moduleId")) || StringUtils.isEmpty(httpServletRequest.getHeader("timestamp"))
                        || StringUtils.isEmpty(httpServletRequest.getHeader("randomStr")) || StringUtils.isEmpty(httpServletRequest.getHeader("sign"))
                        || StringUtils.isEmpty(httpServletRequest.getHeader("key"))
                        ){ // 不存在，认证失败

                    throw new GlobalException("认证失败!!!",-1);
                }

                String moduleId = httpServletRequest.getHeader("moduleId");
                String timestamp = httpServletRequest.getHeader("timestamp");
                String randomStr = httpServletRequest.getHeader("randomStr");
                String sign = httpServletRequest.getHeader("sign");
                String key = httpServletRequest.getHeader("key");

                // 执行认证
                if (moduleId == null) { // 不存在
                    throw new GlobalException("认证失败!!!",-1);
                }
                // 根据moduleId查询库中key
//                Example example = new Example(AuthPerssion.class);
//                example.createCriteria().andEqualTo("moduleId", moduleId);

                AuthPerssion authPerssion = authPerssionMapper.selectAuthPerssionByModuleId(moduleId);
                if(StringUtils.isEmpty(authPerssion)){ // 认证失败
                    throw new GlobalException("认证失败!!!",-1);
                }
                String sysKey = authPerssion.getKey();
                String sysSign = moduleId + timestamp + randomStr + sysKey;
                // 将所有参数进行base加密，并进行校验
                String sysSignEncode = Base64.encode(sysSign);
                if(!sign.equals(sysSignEncode)){ // 校验两者签名不一致
                    throw new GlobalException("认证失败!!!",-1);
                }

                return true;  // 通过所有校验，允许通过

            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {

    }

    public void returnErrorResponse(HttpServletResponse response, CommonResult result)
            throws IOException, UnsupportedEncodingException {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtil.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
